package com.wyz.socket.core.base.frame.send;

import com.wyz.socket.core.base.IoArgs;
import com.wyz.socket.core.base.frame.Frame;
import com.wyz.socket.core.base.packet.AbstractSendPacket;

import java.io.IOException;
import java.nio.channels.ReadableByteChannel;

public class SendEntityFrame extends AbstractSendPacketFrame {
    private final ReadableByteChannel channel;
    private final int unConsumeEntityLength;


    public SendEntityFrame(int entityLength, short identifier, AbstractSendPacket<?> sendPacket, ReadableByteChannel channel) {
        super(Math.min(Frame.MAX_CAPACITY, entityLength), TYPE_ENTITY, FLAG_NON, identifier, sendPacket);
        this.unConsumeEntityLength = entityLength - bodyRemaining;
        this.channel = channel;
    }

    @Override
    protected int consumeBody(IoArgs args) throws IOException {
        if(sendPacket == null){
            return args.fillEmpty(bodyRemaining) ;
        }
        return args.readFrom(channel);
    }

    @Override
    protected Frame buildNextFrame() {
        if (unConsumeEntityLength == 0) {
            return null;
        }
        return new SendEntityFrame(unConsumeEntityLength, getBodyIdentifier(), sendPacket, channel);
    }
}
